import React, { Component } from 'react';
import {
    View, Text, StyleSheet, TouchableOpacity, Image, ScrollView, Modal, ActivityIndicator, PixelRatio
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import DatePicker from 'react-native-datepicker'
import navigationSeevice from '../../../../components/navigation/navigationSeevice';
import { API, API_GENERATE } from '../../../../config/api';
import Upload from '../../../../utils/Upload';
import HTTP from '../../../../utils/http';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import Dictionary from '../../../../utils/dictionary';
import ModalPicDelComponent from '../../../../component/ModalPicDelComponent';
import { enterpriseStyles } from '../../_common/enterpriseStyle';
import { Common } from '../../../../component/common/Common'
import ToastUtil from '../../../../utils/toast';
import { EnterpriseUploadItem } from '../_components/EnterpriseUploadItem'
const scale = GLOBAL.SCALE;
const uploadPic = require('../../../../imgs/store/upload.png');
let deleteIcon = require('../../../../imgs/delete.png');

const modalPicDelCfg = {
    visible: false,
    uri: null,
    delPress: () => { },
    picPress: () => { },
    fileId: '',
    delTextHide: true
}

export class EnterpriseUploadPage extends Component {
    static navigationOptions = ({ navigation }) => {
        return {
            headerTitle: '资质上传',
            headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
            headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
            headerTintColor: style.color.white,
            headerStyle: {
                elevation: 0,
                borderBottomWidth: 0,
                backgroundColor: style.color.themeColor,
            },
            headerTitleStyle: {
                flex: 1,
                textAlign: 'center',
            }
        };
    };

    constructor(props) {
        super(props);
        this.sendData = {
            bizType: 'COMPANY_QUALIFI_INFO',
            companyInfoVO: {
            },
            qualificationList: [],
        };
        modalPicDelCfg.picPress = () => {
            modalPicDelCfg.visible = false;
            modalPicDelCfg.uri = null;
            this.setState({
                previewModalVisible: false,
            });
        }
        this.showImage = []
        this.showDataList = []
        this.qualificationList = []
        this.state = {
            qualificationList: [],
            type: ""
        }

    }

    async componentWillMount () {
        
        let { companyId, corpId, type, qualificationList, showDataList } = this.props.navigation.state.params
        if (showDataList && showDataList.length > 0) {
            this.showDataList = showDataList
        }
        if (!qualificationList||qualificationList.length==0) {
            const qualificationListPage = await HTTP.POST(API_GENERATE(API.QUERT_COMPANY_QUALIFI), { companyId, corpId });
            qualificationList = qualificationListPage.rows || []
            let qualificationTypeList = await Dictionary.get("EC_QUALIFICATION_TYPE");
            let qualificationTypeObj = {}
            qualificationTypeList.forEach(item => {
                const { dictKey, dictName } = item;
                qualificationTypeObj[dictKey] = dictName;
            });
            qualificationList.map((item, index) => {
                item.qualificationTypeText = qualificationTypeObj[item.qualificationType];
            })
        }
        this.setState({
            qualificationList,
            type
        })
        this.sendData.companyInfoVO.companyId = companyId
        this.qualificationList = qualificationList
    }


    async _didPressLargeBtn (type) {
        let isAuditTag = false; expireDateOut = false
        for (let index = 0; index < this.qualificationList.length; index++) {
            const item = this.qualificationList[index];
            if (item.qualificationAddress) {
                if (!item.expireDate) {
                    ToastUtil.showInfo(item.qualificationTypeText + '需填写结束日期');
                    expireDateOut = true
                    return;
                }
                if (new Date(item.expireDate) < new Date()) {
                    ToastUtil.showInfo(item.qualificationTypeText + '结束日期不能小于当前日期');
                    expireDateOut = true
                    return;
                }
            }
            else {
                item.expireDate = null
            }
            if (item.isAuditTag) {
                isAuditTag = true
            }
        }

        if (expireDateOut || isAuditTag) {
            if (isAuditTag) {
                if (type === 'upload') {
                    ToastUtil.showError('企业当前变更审批中，请审批后再操作');
                }
                else if (type === 'save') {
                    ToastUtil.showError('该企业正在变更申请中，无法重复提交变更');
                }
            }
        }
        else {
            console.log(this.qualificationList)
            this.qualificationList.map((item) => {
                if (item.qualificationAddress) {
                    this.sendData.qualificationList.push(item)
                }
            })
            if (type === 'upload') {
                this.setState({ loaded: true })
                const responseData = await HTTP.POST(API_GENERATE(API.UPDATE_CUSTOMER_INFO), this.sendData);
                this.setState({ loaded: false })
                if (responseData) {
                    ToastUtil.showSuccess('您添加的资质已提交,请耐心等待审核');
                    this.timer = setTimeout(() => {
                        this.props.navigation.goBack();
                        this.props.navigation.state.params.refresh();
                    }, 800)
                }
            }
            else if (type === 'save') {
                this.props.navigation.goBack();
                this.props.navigation.state.params.getImage({ qualificationList: this.qualificationList, showDataList: this.showDataList });
            }
        }
    }
    getItemInfo = (value) => {
        let { itemData, showData } = value
        let hasValue = false
        for (let i = 0; i < this.qualificationList.length; i++) {
            let item = this.qualificationList[i];
            if (item.qualificationType == itemData.qualificationType) {
                this.qualificationList[i] = itemData
                hasValue = true
            }
        }
        if (!hasValue) {
            this.qualificationList.push(itemData)
        }
        if (showData.uriListUri.length > 0) {
            let hasValue2 = false
            for (let i = 0; i < this.showDataList.length; i++) {
                let item = this.showDataList[i];
                if (item.qualificationType == showData.qualificationType) {
                    this.showDataList[i] = showData
                    hasValue2 = true
                }
            }
            if (!hasValue2) {
                this.showDataList.push(showData)
            }
        }
        else{
            for (let i = 0; i < this.showDataList.length; i++) {
                let item = this.showDataList[i];
                if (item.qualificationType == showData.qualificationType) {
                    this.showDataList[i] = showData
                }
            }
        }
        console.log(this.qualificationList)
        console.log(this.showDataList)
    }
    render () {
        let qualificationArray = this.state.qualificationList || []
        return (
            <ScrollView style={styles.scrollView} >
                {
                    qualificationArray && qualificationArray.map((item, index) => {
                        return (
                            <View key={index} >
                                <EnterpriseUploadItem
                                    data={item}
                                    getItemInfo={(val) => { this.getItemInfo(val) }}
                                    enlarge={
                                        (val) => {
                                            modalPicDelCfg.visible = true;
                                            modalPicDelCfg.uri = val;
                                            this.setState({
                                                ls: true
                                            })
                                        }}
                                />
                            </View>
                        )
                    })
                }
                <ModalPicDelComponent {...modalPicDelCfg} />
                <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                    {this.state.type === 'upload' ?
                        <TouchableOpacity style={styles.button} onPress={() => this._didPressLargeBtn('upload')}>
                            <Text style={styles.buttonText}>提交</Text>
                        </TouchableOpacity> :
                        <TouchableOpacity style={styles.button} onPress={() => this._didPressLargeBtn('save')}>
                            <Text style={styles.buttonText}>保存</Text>
                        </TouchableOpacity>
                    }
                </View>
            </ScrollView>
        )
    }

}

const styles = StyleSheet.create({
    scrollView: {
        flex: 1,
        backgroundColor: '#fff',
    },
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#fff',
    },
    wrap: {
        width: 345 * scale,
    },
    closeTextCell: {
        position: 'absolute',
        left: 8,
        top: 0,
    },
    productText: {
        fontSize: 14 * scale,
        color: '#404040',
        marginBottom: 8 * scale,
        paddingTop: 14 * scale,
        lineHeight: 14 * scale,
    },
    ocrWrap: {
        width: 375 * scale,
        height: GLOBAL.SCREEN_HEIGHT,
        backgroundColor: 'rgba(0, 0, 0, 0)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadedCell: {
        width: 75 * scale,
        height: 75 * scale,
        backgroundColor: 'rgba(0, 0, 0, .5)',
        borderRadius: 7,
        justifyContent: 'center',
        alignItems: 'center',
    },
    boxUp: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingTop: 15 * scale,
        paddingBottom: 15 * scale,
    },
    label: {
        width: 70 * scale,
        color: '#333',
        fontSize: 14 * scale
    },
    require: {
        fontSize: 14 * scale,
        color: '#D0021B',
    },
    rowStyle: {
        // flex: 1,
        flexDirection: 'row',
        alignItems: 'center'
    },
    xianBox: {
        width: 108 * scale,
    },
    xian: {
        marginLeft: 5 * scale,
        marginRight: 5 * scale,
        color: '#222',
        textAlign: 'center',
        fontWeight: 'bold'
    },
    select: {
        tintColor: '#000',
        transform: [{ 'rotate': '-90deg' }]
    },
    uploadImgBox: {
        borderColor: style.color.themeColor,
        borderWidth: 1,
    },
    close: {
        position: 'absolute',
        right: -8 * scale,
        top: -6 * scale,
        width: 12 * scale,
        height: 12 * scale,
        zIndex: 10
    },
    button: {
        marginTop: 20 * scale,
        marginBottom: 50 * scale,
        width: 99 * scale,
        height: 39 * scale,
        backgroundColor: '#0E7FFD',
        borderRadius: 15 * scale,
        justifyContent: 'center',
        alignItems: 'center',
    },
    buttonText: {
        fontSize: 14 * scale,
        color: '#fff'
    },
})